import json
import redis as redisConnect
from flask import Flask, request
from flask_cors import CORS
import uuid

redis = redisConnect.StrictRedis(host='47.110.47.209', port=15001, db=0, decode_responses=True, charset="UTF-8", encoding="UTF-8")
app = Flask(__name__)
CORS(app, supports_credentials=True, resources=r'/*')


@app.route('/keyword', methods=['POST'])
def create_keyword():
    keywordId = str(uuid.uuid1())
    value = request.json
    value["id"] = keywordId
    redis.set(keywordId, json.dumps(value, ensure_ascii=False))
    return keywordId


@app.route('/keyword/<string:keyword_id>', methods=['PUT'])
def update_keyword(keyword_id):
    if not redis.exists(keyword_id):
        raise Exception("没有对应关键词")
    value = request.json
    value["id"] = keyword_id
    redis.set(keyword_id, json.dumps(value, ensure_ascii=False))
    print(redis.get(keyword_id))
    return keyword_id


@app.route('/keyword/<string:keyword_id>', methods=['DELETE'])
def delete_keyword(keyword_id):
    redis.delete(keyword_id)
    return keyword_id


@app.route('/keyword/list', methods=['GET'])
def keywords():
    keywordList = []
    pipe = redis.pipeline()
    for key in redis.keys():
        print(key)
        pipe.get(key)
    for v in pipe.execute():
        keywordList.append(json.loads(v))
    print(keywordList)
    return json.dumps(keywordList, ensure_ascii=False)


def main():
    redis.delete("682fffd7-bf40-11ec-b6ed-a0510bfb240e")
    app.run()


if __name__ == '__main__':
    main()
